package com.dailyblue.java.boot.security.project.filter;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.boot.commons.util.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
public class CheckLoginFilter extends BasicAuthenticationFilter {

    private StringRedisTemplate stringRedisTemplate;

    public CheckLoginFilter(AuthenticationManager authenticationManager, StringRedisTemplate stringRedisTemplate) {
        super(authenticationManager);
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        if (token != null) {
            String id = JwtConfig.getMemberIdByJwtToken(token);
            ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
            String token1 = value.get("token:" + id);
            if (token.equals(token1)) {
                List<GrantedAuthority> authorities = JSONArray.parseArray(value.get("powers:" + id),GrantedAuthority.class);
                UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(id, token, authorities);
                // 代表用户是登陆状态
                SecurityContextHolder.getContext().setAuthentication(upat);
            }
        }
        chain.doFilter(request, response);
    }
}

